package com.dahuyou.trigger.http;

import com.dahuyou.types.util.HttpURLClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 模拟客户端服务器
 */
//@RestController
@Controller
@RequestMapping("/client")
public class ClientServerController {
    private static final String oauthURl = "http://localhost:8899/authServer/exchangeAccessTokenByCode";

    @RequestMapping("/prepareAuth")
    public String methodOne(HttpServletRequest request) {
        request.setAttribute("word", "小姐姐，我需要你的授权，才能看到你的个人信息！");
        return "test";
    }

    /**
     * 接收授权服务器授权码的回调接口
     * @param request
     * @return
     */
    @RequestMapping("/receiveAuthCode")
    @ResponseBody
    public String receiveAuthCode(HttpServletRequest request) {
        //授权码许可流程，DEMO CODE
        String code = request.getParameter("code");
        Map<String, String> params = new HashMap<String, String>();
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        params.put("app_id", "APPID_RABBIT");
        params.put("app_secret", "APPSECRET_RABBIT");
        System.out.println("start post code for token ...");
        String accessToken = HttpURLClient.doPost(oauthURl, HttpURLClient.mapToStr(params));
        System.out.println("accessToken:" + accessToken);
       /* //使用 accessToken 请求受保护资源服务
        Map<String, String> paramsMap = new HashMap<String, String>();
        paramsMap.put("app_id", "APPID_RABBIT");
        paramsMap.put("app_secret", "APPSECRET_RABBIT");
        paramsMap.put("token", accessToken);
        String result = HttpURLClient.doPost(protectedURl, HttpURLClient.mapToStr(paramsMap));*/
        return "成功拿到了access_token: " + accessToken + ", 接着就可以拿来访问受保护资源了！";
    }
}
